package com.example.publishDemo.Controller;

import com.example.publishDemo.Mapper.ArticleMapper;
import com.example.publishDemo.Mapper.UserMapper;
import com.example.publishDemo.Model.*;
import com.example.publishDemo.Service.ArticleService;
import com.example.publishDemo.Tools.Tool;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.rmi.CORBA.Util;
import javax.xml.ws.Service;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static java.util.Objects.isNull;

@CrossOrigin(origins = "http://localhost:8080")
@RestController
@RequestMapping("/article")
public class ArticleController {

    @Resource
    RedisTemplate redisTemplate;

    @Resource
    ArticleService service;

    @Resource
    UserMapper userMapper;

    @GetMapping("/getAllCollectArticle")
    public AjaxResult GetAllCollectArticle(@RequestParam int u_id,int start,int end) {
        List<Integer> article = service.GetAllCollectArticle(u_id);
        List<Article> collect = article.stream().map(articleId -> service.getOne(articleId)).skip(start).limit(end).collect(Collectors.toList());

        return AjaxResult.success(collect);
    }

    @GetMapping("/delHistory")
    public AjaxResult delHistory(@RequestParam int u_id) {
        String key = String.format("history:%d", u_id);
        redisTemplate.delete(key);
        return AjaxResult.success(true);
    }

    @GetMapping("/history")
    public AjaxResult history(@RequestParam int u_id) {
        String key = String.format("history:%d", u_id);
        Map entries = redisTemplate.opsForHash().entries(key);
        return AjaxResult.success(entries);
    }

    @PostMapping("/change")
    public AjaxResult change(@RequestBody(required = false) Article article){
        article.setDate(LocalDate.now());
        int i = service.change(article);
        if(i > 0){
            return AjaxResult.success(true);
        }
        return AjaxResult.error("err",false);
    }

    @GetMapping("/getArticleCount")
    public AjaxResult getArticleCount(){
        int i = service.countAllArticle();
        return AjaxResult.success(i);
    }

    @GetMapping("/report")
    public AjaxResult report(@RequestParam int a_id,int u_id) {
        ArticleReport report = service.isReport(a_id, u_id);
        if(report != null && report.getProcess() == 0) return AjaxResult.error("我们正在加紧时间审核文章内容，请耐心等待！",false);
        if (report.getProcess() == 1) {
            service.reReport(report.getR_id());
            return AjaxResult.success(true);
        }
        service.report(a_id, u_id);
        return AjaxResult.success(true);
    }

    @GetMapping("/isStar")
    public AjaxResult isStar(@RequestParam int a_id,int u_id) {
        Boolean star = service.isStar(a_id, u_id);
        if (true) {
            return AjaxResult.success(true);
        }
        return AjaxResult.error("err",false);
    }

    @GetMapping("/staredNum")
    public AjaxResult staredNum(@RequestParam int a_id) {
        int i = service.staredNum(a_id);
        return AjaxResult.success(i);
    }

    @GetMapping("/star")
    public AjaxResult stared(@RequestParam int u_id,int a_id) {
        if(service.isStar(u_id, a_id)){
            service.delStar(u_id, a_id);
            return AjaxResult.error("已取消收藏");
        }
        service.star(u_id, a_id);
        return AjaxResult.success("收藏成功！",true);
    }

    @PostMapping("/save")
    public AjaxResult save(@RequestBody(required = false) Article article){
        article.setDate(LocalDate.now());
        int i = service.save(article);
        if(i > 0){
            return AjaxResult.success(true);
        }
        return AjaxResult.error("err",false);
    }

    @GetMapping("/getOne")
    public AjaxResult getOne(@RequestParam int a_id) {
        Article article = service.getOne(a_id);
        return AjaxResult.success(article);
    }

    @GetMapping("/articleRangeNum")
    public AjaxResult articleRangeNum(@RequestParam String activeName, String keyword, int u_id) {
        if (activeName == "" || activeName == null || activeName.length() < 1) {
            activeName = "first";
        }
        if (keyword == "" || keyword == null || keyword.trim().length() < 1) {
            keyword = "";
        }
        if(userMapper.findById(u_id) == null) return AjaxResult.error("err",false);

        int i = service.articleRangeNum(activeName, keyword, u_id);
        return AjaxResult.success(i);
    }

    @GetMapping("/articleNumByTag")
    public AjaxResult articleNumByTag(@RequestParam String tag) {
        int numByTag = service.articleNumByTag(tag);
        return AjaxResult.success(numByTag);
    }

    @GetMapping("/communityArticle")
    public AjaxResult communityArticle(@RequestParam int start, int end, String tag) {
        List<Article> articles = service.getArticleForTag(tag);
        return AjaxResult.success(Tool.subList(articles, start, end));
    }

    @GetMapping("/articleRange")
    public AjaxResult articleRange(@RequestParam int start, int end, String activeName, String keyword, int u_id) {
//                List<Article> range = service.rangeForTime2(start, end);
        if(start < 0){
            start = 0;
        }
        if (end < start ) {
            end = start + 5;
        }
        if (activeName == "" || activeName == null || activeName.length() < 1) {
            activeName = "first";
        }
        if (keyword == "" || keyword == null || keyword.trim().length() < 1) {
            keyword = "";
        }
        if(userMapper.findById(u_id) == null) return AjaxResult.error("err",false);

        List<Article> list = service.articleRange( start, end, activeName, keyword, u_id);
        return AjaxResult.success(list);
    }

    @GetMapping("/articleForCommend")
    public AjaxResult articleRecommend(){
        List<Article> commends = service.forCommend();
        return AjaxResult.success(commends);
    }

    @GetMapping("/views")
    public AjaxResult increaseViews(@RequestParam int a_id,int u_id){
        int i = service.increaseView(a_id);

        //留下浏览记录
        String key = String.format("history:%d", u_id);
        Article article = service.getOne(a_id);
        article.setContent("");     //不携带不展示的内容，节约空间
        redisTemplate.opsForHash().put(key, Tool.getCurrentDateTime(),article);
        //计入当日访问量
        String dailyView = String.format("daily-views");
        String dailyViewsKey = String.format("daily-views:%s", Tool.getCurrentDate()); // 使用日期作为键
        redisTemplate.opsForZSet().incrementScore(dailyView, dailyViewsKey, 1);

        //取出过去七天的访问数值

        if (i > 0) {
            return AjaxResult.success(true);
        }
        return AjaxResult.error("err", false);
    }

    @GetMapping("/score")
    public AjaxResult averageScore(@RequestParam int u_id, int a_id ,double flag){
        List<ArticleScore> score = service.isScore(u_id, a_id);
        if (!score.isEmpty() && score.size() > 0) {
            return AjaxResult.error("请勿多次评分", false);
        }
        int i = service.averageScore(flag,a_id);
        int s = service.saveScore(u_id, a_id, flag);
        if (i > 0 && s > 0) {
            return AjaxResult.success(true);
        }
        return AjaxResult.error("err", false);
    }

    @GetMapping("/isScore")
    public AjaxResult isScore(@RequestParam int u_id, int a_id ) {
        List<ArticleScore> score = service.isScore(u_id, a_id);
        if (!score.isEmpty() && score.size() > 0) {
            return AjaxResult.success("ok",score.get(0).getScore());
        }
        return AjaxResult.error("err", false);
    }

}
